/*
 * screen.c
 *
 *  Created on: 2024-4-16
 *      Author: NI
 */
#include <screen/screen.h>
#include "errno.h"
#include <stdio.h>
#include <stdlib.h>

screen_window_t screen_win;
screen_context_t  screen_ctx;
screen_buffer_t *screen_buf;

int display_setting(){
	int ret = EOK;

	int screen_ndisplays;
	ret = screen_get_context_property_iv(screen_ctx, SCREEN_PROPERTY_DISPLAY_COUNT, &screen_ndisplays);
	if (ret) {
		printf("screen_get_context_property_iv(SCREEN_PROPERTY_DISPLAY_COUNT)");
		return ret;
	}

	screen_display_t* screen_disp;
	screen_disp = calloc(screen_ndisplays, sizeof(*screen_disp));
	if (screen_disp == NULL) {
		fprintf(stderr, "could not allocate memory for display list\n");
		return 1;
	}

	ret = screen_get_context_property_pv(screen_ctx, SCREEN_PROPERTY_DISPLAYS,(void**)screen_disp);
	if (ret) {
		perror("screen_get_context_property_ptr(SCREEN_PROPERTY_DISPLAYS)");
		free(screen_disp);
		return ret;
	}


	int want_id = 1; int i = 0;
	for (i = 0; i < screen_ndisplays; ++i) {
		int actual_id = 0;            // invalid
		screen_get_display_property_iv(screen_disp[i], SCREEN_PROPERTY_ID, &actual_id);
		printf("actual_id:%d, want_id:%d\n", actual_id, want_id);
		if (want_id == actual_id) {
			break;
		}
	}

	if (i >= screen_ndisplays) {
		fprintf(stderr, "couldn't find display \n");
		free(screen_disp);
		return ret;
	}

	ret = screen_set_window_property_pv(screen_win, SCREEN_PROPERTY_DISPLAY, (void**)&screen_disp[i]);
	if (ret) {
		perror("screen_set_window_property_ptr(SCREEN_PROPERTY_DISPLAY)");
		free(screen_disp);
		return ret;
	}
	free(screen_disp);

	return ret;
}

int screen_init(){
	int ret = EOK;
	ret = screen_create_context(&screen_ctx, 0);
	if(ret)	return ret;

	ret = screen_create_window(&screen_win, screen_ctx);
	if(ret)	return ret;

	ret = display_setting();
	if(ret) return ret;

	return ret;
}

